<?php

namespace Framework\Foundation\Route;

use Framework\Foundation\Request\ServerRequestProxy;
use Psr\Http\Message\ServerRequestInterface;

class RouterHelper
{
    public $request;

    public function __construct($request = null)
    {
        $this->request = $request ?? ServerRequestProxy::fromGlobalsAndHandleJson();
    }

    public function extractRouteInfo(ServerRequestInterface $serverRequest)
    {
        $method = $serverRequest->getMethod();

        $pattern1 = "/\/index\.php\??/";
        $ret = preg_replace($pattern1, '', $_SERVER['REQUEST_URI']);
        $pattern2 = "/&.*/";
        $route = preg_replace($pattern2, '', $ret);

        if (false !== $position = strpos($route, '?')) {
            $route = substr($route, 0, $position);
        }

        return ['method' => $method, 'ajax_method' => $serverRequest->getAjaxMethod(), 'route' => $route];
    }

    public function extractRestResourceFromRoute($routeInfo)
    {
        $position = strrpos($routeInfo['route'], '/');
        return substr($routeInfo['route'], $position + 1);
    }

    /**
     * GET, POST, PUT, DEL
     * /{module}/{version}/{resource}/{resource_id}/{relation}
     * module+version 是restFul的路由 决定走哪个restFul控制器,多个版本可指向同一个控制器，在控制器中做区分
     * @param ServerRequestInterface $serverRequest
     * @return array
     * @throws \Exception
     */
    public function getRestFulRouteInfo(ServerRequestInterface $serverRequest)
    {
        return $this->extractRouteInfo($serverRequest);
    }
}
